<template>
    <div class="table-box">
        <ProTable ref="proTable" title="用户列表" :columns="columns" :request-api="getTableList" :init-param="initParam"
            :data-callback="dataCallback">
            <!-- 表格 header 按钮 -->
            <template #tableHeader="scope">
                <el-button type="primary" class="standard-btn" :icon="CirclePlus" @click="openDiolg('新增', null)">
                    新增供应商
                </el-button>
                <!-- <el-button type="info" plain icon="Upload"
                    @click="() => { ExcelRef.open('/staff/socialfund/importSocFee') }"
                    v-hasPermi="['system:user:import']">导入</el-button>
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['system:user:export']">导出</el-button> -->

            </template>
            <!-- 表格操作 -->
            <template #operation="scope">
                <el-button type="primary" link :icon="View" @click="openDiolg('查看', scope.row)">
                    查看
                </el-button>
                <el-button type="primary" link :icon="EditPen" @click="openDiolg('编辑', scope.row)">
                    编辑
                </el-button>
                <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
                    删除
                </el-button>
            </template>
        </ProTable>
        <ExcelUpload ref="ExcelRef" title="导入demo" type="1" :templateParams="templateParams">
        </ExcelUpload>
    </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, tabBarProps } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import {
    ColumnProps,
} from "@/components/ProTable/interface";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    deviceNumList,
    devTypeList,
    devOnlineStatusList,
    devUseStatusList,
    findLabel,
} from "@/utils/stata";
import {
    listSupplier,
    getSupplier,
    delSupplier,
    addSupplier,
    updateSupplier
} from "@/api/zc/SupplierMagment";
import { getDicts } from "@/api/system/dict/data";
import { useHandleData } from "@/hooks/useHandleData";
const proxy = getCurrentInstance()?.proxy;
const emit = defineEmits(["changeItem"]);
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));
const router = useRouter();
const ExcelRef = ref(null);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<any>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
    return { list: data.rows, total: data.total };
};
onMounted(() => {
    setTimeout(() => {
        const { add, ...query } = router.currentRoute.value.query;
        if (add == 0) {
            openDiolg('新增', null)

            // 成功后移除add参数
            router.replace({ query });
        }
    }, 1000)
})

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
    return listSupplier(params);
};
const templateParams = {
    templateName: "demo模板",
    templateUrl: "system/user/importTemplate",
    templateType: 0,
    templateObj: {}
}

// 表格配置项
const columns: any = [
    {
        prop: 'supplierName',
        label: '供应商名称',
        search: {
            el: 'input'
        }
    },
    {
        prop: 'business',
        label: '主营品类',
        search: {
            el: 'input'
        }
    },
    {
        prop: 'contactor',
        label: '联系人',
        search: {
            el: 'input'
        }
    },
    {
        prop: 'phone',
        label: '电话',
        search: {
            el: 'input'
        }
    },
    {
        prop: 'supplierAddress',
        label: '供应商地址',
        search: {
            el: 'input'
        }
    },
    {
        prop: 'email',
        label: '邮箱地址',
        search: {
            el: 'input'
        }
    },
    {
        prop: 'status',
        label: '合作状态',
        render: (scope) => {
            return (
                    <el-switch
                    v-model={scope.row.status}
                    active-text="是"
                    inactive-text="否"
                    active-value={0}
                    inactive-value={1}
                    onClick={() => changeStatus(scope.row, 'isArrive')}
                />
            )

        },
        enum: [
            {
                label: '合作',
                value: 0
            },
            {
                label: '未合作',
                value: 1
            },
        ],
        search: {
            el: 'select'
        }
    },
    {
        prop: 'operation',
        label: '操作',
        fixed: 'right',
        width: 330
    }
];
const changeStatus = async (row: any, key: string) => {
    // await useHandleData(updateSign, { ...row, key: row[key] == 1 ? 0 : 1 }, `切换状态`);
    await updateSupplier({ ...row, key: row[key] == 1 ? 0 : 1 });
      ElMessage.success({ message: `调整合作状态成功！` });
    proTable.value?.getTableList();
};
// 删除用户信息
const deleteAccount = async (params: any) => {
    const ids = params.id
    await useHandleData(delSupplier, ids, '是否删除编号为' + ids + '的数据');
    proTable.value.getTableList();
};
//模拟 调用接口
const PromiseDel = () => new Promise((resolve, reject) => resolve(true))

/** 导出按钮操作 */
function handleExport() {
    proxy.download("system/user/export", {

    }, `user_${new Date().getTime()}.xlsx`);
};

const openDiolg = async (title: string, rowData: any) => {
    let params: any = {
        title,
        isView: title === "查看",
        rowData: { ...rowData },
        api: title === "新增" ? addSupplier : title === "编辑" ? updateSupplier : undefined,
        getTableList: proTable.value?.getTableList,
    };
    if (title === "新增") {
        params.rowData.zcSupplierCertList = []
    }else{
        let {data} = await getSupplier(rowData.id)
        params.rowData = data;
    }
    emit("changeItem", "1", params, title);
};
</script>
